<?php

App::uses('AppController', 'Controller');
App::uses('AuthComponent', 'Controller/Component');

/**
 * Admin controller
 *
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers/pages-controller.html
 */
class AdminController extends AppController
{

    public $name = 'Admin';
    public $components = array(
        'Acl',
        'Auth' => array(
            'authorize' => array(
                'Actions' => array('actionPath' => 'controllers')
            ),
            'authenticate' => array(
                'Form' => array(
                    'fields' => array('username' => 'email')
                )
            )
        ),
    );
    public $uses = array('User');

    public function beforeFilter()
    {
        parent::authorizeAdmin();
    }

    public function admin_index()
    {
        $this->render('/Admin/index');
    }

    /**
     * login
     * @return type
     */
    public function admin_login()
    {
        if ($this->request->is('POST')) {
            if (isset($this->request->data['User'])) {
                $this->User->clear();
                $this->User->set($this->request->data['User']);

                $user = $this->User->find('first', array(
                    'conditions' => array(
                        array('User.email' => $this->User->data['User']['email']),
                        array('User.password' => AuthComponent::password($this->User->data['User']['password'])),
                        array('User.groupId' => Configure::read('admin_group_id'))
                    )
                ));

                if (!$user || !count($user)) {
                    $this->Session->setFlash(__('Your username or password was incorrect.'), 'default', array('class' => 'alert alert-warning'));
                } else {
                    $admin_session = array(
                        'id' => $user['User']['id'],
                        'email' => $user['User']['email'],
                        'firstName' => $user['User']['firstName'],
                        'lastName' => $user['User']['lastName'],
                        'groupId' => $user['User']['groupId']
                    );

                    $this->Session->write('ADMIN_SESSION', $admin_session);
                    $this->Auth->login($admin_session);

                    if ($this->Session->read('URL_REFERER')) {
                        return $this->redirect($this->Session->read('URL_REFERER'));
                    } else {
                        return $this->redirect(array('admin' => true, 'controller' => 'admin', 'action' => 'index'));
                    }
                }
            }
        }

        $this->render('/Admin/login');
    }

    /**
     * logout
     * @return type
     */
    public function admin_logout()
    {
        return $this->redirect($this->Auth->logout());
    }

}
